<template>
  <div class="page page-certificate page-account has-headbar">
    <head-bar :title="$route.meta.title" />
    <section class="form-section">
      <div class="form-item">
        <div class="label">手机号</div>
        <van-field
          class="form-field"
          v-model="phone"
          placeholder="请输入手机号"
          maxlength="11"
          v-validate="'required|phone'"
          name="phone"
        />
      </div>
      <div class="form-item">
        <div class="label">验证码</div>
        <van-field
          class="form-field"
          v-model="code"
          placeholder="请输入验证码"
          maxlength="6"
          v-validate="'required'"
          name="code"
        >
          <van-button slot="button" size="small" type="primary" class="verycode" :disabled="verycodeDisabled" @click="verycodeEvent">{{vericodeText}}</van-button>
        </van-field>
      </div>
      <van-button @click="submitEvent" class="submit-button" :disabled="submitStatus" :loading="submitStatus" type="primary" size="large">提交</van-button>
    </section>
  </div>
</template>

<script>
import { API_CERTIFICATE, API_CERTIFICATE_MSG } from '@/service/account'
import { wxjsdkMixin } from '@/components/mixins'
const countDown = 60
export default {
  mixins: [wxjsdkMixin],
  name: 'change-phone',
  data () {
    return {
      phone: '',
      code: '',
      verycodeDisabled: false,
      countDown: countDown,
      submitStatus: false
    }
  },
  computed: {
    vericodeText () {
      return this.verycodeDisabled ? `已发送(${this.countDown})` : '获取验证码'
    }
  },
  mounted () {
    this.wechatHideMenu()
  },
  methods: {
    verycodeEvent () {
      if (!/^(1[3456789]\d{9})$/.test(this.phone)) {
        this.$toast('请填写手机号码')
        return
      }
      this.verycodeDisabled = true
      API_CERTIFICATE_MSG(this.phone).then(resData => {
      })
      let timer = setInterval(() => {
        this.countDown--
        if (this.countDown === 0) {
          clearInterval(timer)
          this.countDown = countDown
          this.verycodeDisabled = false
        }
      }, 1000)
    },
    submitEvent () {
      this.$validator.validate().then(result => {
        if (result) {
          this.submitStatus = true
          let reqData = {
            phone: this.phone,
            code: this.code
          }
          API_CERTIFICATE(reqData).then(() => {
            let userInfo = { ...this.$store.getters.getUserInfo }
            userInfo.phoneNum = this.phone
            this.$store.dispatch('saveUserInfo', userInfo)
            this.$toast('认证成功！')
            this.$router.go(-1)
          }).catch(() => {
            this.submitStatus = false
          })
        } else {
          this.$toast(this.errors.all()[0])
        }
      })
    }
  }
}
</script>

<style lang="less">
@import "../assets/styles/account.less";
</style>
